package com.dingreading.cloud.gateway.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * mono构建返回内容
 */
public class MonoUtil {

    /**
     * 构建返回内容
     */
    public static Mono<Void> writeResponse(ServerHttpResponse response, int st, String msg) {
        JSONObject message = new JSONObject();
        message.put("st", st);
        message.put("msg", msg);
        byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.OK);
        // 指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    /**
     * 构建返回内容
     */
    public static Mono<Void> writeResponse(ServerHttpResponse response, int st, String msg, Object data) {
        JSONObject message = new JSONObject();
        message.put("st", st);
        message.put("msg", msg);
        message.put("data", data);
        byte[] bits = message.toJSONString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.OK);
        // 指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

}
